<script setup>
import { useRoute } from 'vue-router';
import { onMounted, ref, watch } from 'vue';
import { zodResolver } from '@primevue/forms/resolvers/zod';
import { useToast } from 'primevue/usetoast';
import { z } from 'zod';
import { getPageContent, updatePage } from '@/api/backend/content';
import { uploadPicture } from '@/api/backend/upload';

const breadcrumbHome = ref({ icon: 'pi pi-home', to: '/' });
const breadcrumbItems = ref([{ label: '内容管理' }, { label: '内容管理' }]);
const route = useRoute();
const toast = useToast();
const isSubmitting = ref(false);
const isLoading = ref(false);

// 初始化表单值
const initialValues = ref({
    cate_id: '',
    content: '',
    piclist: []
});

// Zod 验证模式
const schema = z.object({
    content: z.string().min(1, { message: '内容不能为空' })
});

// 表单解析器
const resolver = zodResolver(schema);

// 加载内容数据（添加防抖）
let abortController = null;
const loadContent = async () => {
    try {
        // 取消之前的请求
        if (abortController) {
            abortController.abort();
        }
        abortController = new AbortController();

        isLoading.value = true;
        initialValues.value.cate_id = route.query.classid;

        const { code, data, message } = await getPageContent(route.query.classid, {
            signal: abortController.signal
        });

        if (code === 200) {
            initialValues.value = { ...data, cate_id: route.query.classid };
        } else {
            throw new Error(message || '获取内容失败');
        }
    } catch (error) {
        initialValues.value.content = '';
        if (error.name !== 'AbortError') {
            toast.add({
                severity: 'error',
                summary: '加载失败',
                detail: error.message,
                life: 3000
            });
        }
    } finally {
        isLoading.value = false;
        abortController = null;
    }
};
const showSuccess = (summary, detail = '') => {
    toast.add({ severity: 'success', summary, detail, life: 3000 });
};

const showError = (summary, detail = '') => {
    toast.add({ severity: 'error', summary, detail, life: 3000 });
};
const uploadImage = async () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';
    input.onchange = async (e) => {
        const file = e.target.files[0];
        // console.log(file);
        const formData = new FormData();
        // 将字段名从 'image' 改为 'file'
        formData.append('file', file); // 🚩 关键修改点
        // console.log('FormData:', [...formData.entries()]);

        try {
            const { code, data } = await uploadPicture(formData);
            if (code === 200) {
                console.log(data);
                initialValues.value.piclist.push({ url: data.url, title: '' });
                showSuccess('图片上传成功');
            }
        } catch (error) {
            showError('上传失败', error.message);
        }
    };
    input.click();
};

// 初始化加载和参数变化监听
onMounted(loadContent);
watch(
    () => route.query.classid,
    (newVal, oldVal) => {
        if (newVal && newVal !== oldVal) {
            loadContent();
        }
    }
);

// 表单提交处理
const onFormSubmit = async ({ valid }) => {
    if (!valid || isSubmitting.value) return;

    isSubmitting.value = true;
    try {
        const { code, message } = await updatePage({
            ...initialValues.value,
            cate_id: route.query.classid // 确保使用最新ID
        });

        if (code === 200) {
            toast.add({
                severity: 'success',
                summary: '提交成功',
                life: 3000
            });
        } else {
            throw new Error(message || '更新内容失败');
        }
    } catch (error) {
        toast.add({
            severity: 'error',
            summary: '提交失败',
            detail: error.message,
            life: 3000
        });
    } finally {
        isSubmitting.value = false;
    }
};
</script>

<template>
    <div>
        <Breadcrumb :home="breadcrumbHome" :model="breadcrumbItems" />
        <div class="card">
            <Form v-slot="$form" :resolver="resolver" :initial-values="initialValues" @submit="onFormSubmit" class="flex flex-col gap-4">
                <div v-if="isLoading" class="text-center p-4">
                    <ProgressSpinner style="width: 50px; height: 50px" />
                    <p class="mt-2">内容加载中...</p>
                </div>

                <div v-else>
                    <div class="flex items-center mb-2">
                        <label for="pic" class="block font-bold mr-3">组图</label>
                        <div class="flex flex-wrap items-start gap-4">
                            <ButtonGroup>
                                <Button label="选择" icon="pi pi-folder-open" />
                                <Button label="上传" icon="pi pi-upload" @click="uploadImage" />
                            </ButtonGroup>
                        </div>
                    </div>
                    <div class="flex flex-col gap-1">
                        <div v-for="(pic, index) in initialValues.piclist" :key="index" class="flex items-center gap-2">
                            <img :src="pic.url" class="w-16 h-16 rounded" />
                            <InputText v-model.trim="pic.title" required="true" fluid />
                            <Button icon="pi pi-times" @click="initialValues.piclist.splice(index, 1)" />
                        </div>
                    </div>
                    <div class="flex flex-col gap-1">
                        <Editor
                            v-model="initialValues.content"
                            name="content"
                            editor-style="height: 320px"
                            :pt="{
                                content: { class: 'min-h-[200px]' },
                                toolbar: { class: 'border-round-top' }
                            }"
                            :disabled="isLoading"
                        />
                        <Message v-if="$form.content?.invalid" severity="error" size="small" variant="simple">
                            {{ $form.content.error?.message }}
                        </Message>
                    </div>
                </div>

                <Button type="submit" severity="secondary" :label="isSubmitting ? '保存中...' : '保存'" :disabled="isSubmitting || isLoading" :loading="isSubmitting" />
            </Form>
        </div>
    </div>
</template>
